@echo off

@REM Parameter description：
@REM $1 - Application project path: apps\tuyaos_zigbee_light_sample
@REM $2 - Application project name: tuyaos_zigbee_light_sample
@REM $3 - Application project version: 1.0.0
@REM $4 - Application project command： build/clean
@REM .\build_app.bat apps\tuyaos_zigbee_light_sample tuyaos_zigbee_light_sample 1.0.0 clean


set APP_PATH=%1
set APP_NAME=%2
set APP_VERSION=%3
set BUILD_COMMAND=%4
if "%BUILD_COMMAND%"=="" (
    set BUILD_COMMAND=build
)

set _BUILD=_build
set SCRIPT_PATH=.\tools\scripts
set APP_BUILD_PATH=%APP_PATH%\%_BUILD%

@echo APP_PATH=%APP_PATH%
@echo APP_NAME=%APP_NAME%
@echo APP_VERSION=%APP_VERSION%
@echo BUILD_COMMAND=%BUILD_COMMAND%
@echo APP_BUILD_PATH=%APP_BUILD_PATH%
@echo SCRIPT_PATH=%SCRIPT_PATH%


set str=%PATH%
set remain=%str%
set PYTHON_PATH=""
:loop
for /f "tokens=1* delims=;" %%a in ("%remain%") do (
 echo %%a |  findstr /i "Python3" > null && ("%%a"\python --version 2>null && (set PYTHON_PATH="%%a"))
 rem 
 set remain=%%b
)
if defined remain goto :loop
del null
@REM echo %PYTHON_PATH%

if %PYTHON_PATH%=="" (call:fatal "not install python3!!!")

if "%APP_PATH%"=="" (call:fatal "no app path!")
if "%APP_NAME%"=="" (call:fatal "no app name!")
if "%APP_VERSION%"=="" (call:fatal "no app version!")

set local_path=%~dp0
@echo local_path=%local_path%

if "%BUILD_COMMAND%"=="build" (
    chdir %SCRIPT_PATH%
    %PYTHON_PATH%\python app_prepare.py %APP_PATH% %APP_NAME% %APP_VERSION% %BUILD_COMMAND%
    chdir %local_path%
)

chdir %APP_BUILD_PATH%
%PYTHON_PATH%\python build.py %APP_PATH% %APP_NAME% %APP_VERSION% %BUILD_COMMAND%
chdir %local_path%


goto:eof

:fatal
    echo error: %1
    exit 1
goto:eof

